package com.store.controller;

import com.store.annotation.RequireRole;
import com.store.common.Result;
import com.store.dto.LoginRequest;
import com.store.dto.LoginResponse;
import com.store.dto.UserInfoDTO;
import com.store.entity.User;
import com.store.service.AuthService;
import com.store.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin
public class AuthController {
    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private AuthService authService;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseEntity<LoginResponse> login(@RequestBody LoginRequest loginRequest) {
        logger.info("收到登录请求: username={}", loginRequest.getUsername());
        try {
            LoginResponse response = authService.login(loginRequest);
            logger.info("登录成功: username={}, role={}", response.getUsername(), response.getRole());
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("登录失败: username={}, error={}", loginRequest.getUsername(), e.getMessage());
            throw e;
        }
    }

    @PostMapping("/register")
    public ResponseEntity<Void> register(@RequestBody LoginRequest registerRequest) {
        logger.info("收到注册请求: username={}", registerRequest.getUsername());
        try {
            authService.register(registerRequest);
            logger.info("注册成功: username={}", registerRequest.getUsername());
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            logger.error("注册失败: username={}, error={}", registerRequest.getUsername(), e.getMessage());
            throw e;
        }
    }

    @PostMapping("/logout")
    @RequireRole({"ADMIN", "SUPER_ADMIN"})
    public Result<Void> logout() {
        // 实际项目中可能需要处理token的失效
        return Result.success();
    }

    @GetMapping("/user")
    public Result<UserInfoDTO> getCurrentUser(@RequestAttribute("username") String username) {
        logger.info("获取当前用户信息: username={}", username);
        User user = userService.findByUsername(username);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }
        
        UserInfoDTO userInfo = new UserInfoDTO();
        userInfo.setId(user.getId());
        userInfo.setUsername(user.getUsername());
        userInfo.setRole(user.getRole());
        
        return Result.success(userInfo);
    }
} 